import { pushTarget, popTarget } from "./dep.js";

let id = 0;
class Watcher {
  constructor(vm, exprOrFn, callback, options) {
    this.vm = vm;
    this.exprOrFn = exprOrFn;
    this.callback = callback;
    this.options = options;
    this.getter = exprOrFn; // 将内部传过来的回调函数， 放到getter属性上
    this.id = id++;

    this.get(); // 调用get方法， 会让渲染watcher执行
  }

  get() {
    pushTarget(this); // 把watcher存起来
    this.getter(); // 渲染watcher的执行
    popTarget(); // 移出watcher
  }

  update() {
    queueWatcher(this);
    // this.getter();
  }

  run() {
    this.get();
  }
}

let queue = [];
let has = {};


function queueWatcher(watcher) {
  let id = watcher.id;
  if (has[id] == null) {
    queue.push(watcher);
    has[id] = true;
    setTimeout(() => {
      queue.forEach(watcher => watcher.run());
      queue = [];
      has = {};
    }, 0)
  }
}
export default Watcher;